package qeug.shsh.facde.controller;


import com.drew.lang.annotations.NotNull;
import com.huawei.shade.org.apache.commons.logging.Log;
import com.huawei.shade.org.apache.commons.logging.LogFactory;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.AppInfo;
import kd.bos.entity.AppMetadataCache;
import kd.bos.entity.param.AppCustomParam;
import kd.bos.openapi.common.custom.annotation.ApiController;
import kd.bos.openapi.common.custom.annotation.ApiPostMapping;
import kd.bos.openapi.common.custom.annotation.ApiRequestBody;
import kd.bos.openapi.common.custom.annotation.ApiResponseBody;
import kd.bos.openapi.common.result.CustomApiResult;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.permission.api.IUserService;
import kd.bos.permission.model.UserParam;
import kd.bos.service.ServiceFactory;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.license.LicenseServiceHelper;
import kd.bos.servicehelper.parameter.SystemParamServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;
import qeug.shsh.facde.RequestContextService;
import qeug.shsh.facde.info.JobsBean;
import qeug.shsh.facde.info.OrgsBean;
import qeug.shsh.facde.info.PaymentModel;
import qeug.shsh.facde.info.UserModel;
import qeug.shsh.facde.resultext.PaymentResultExt;
import qeug.shsh.facde.resultext.UserResultExt;

import javax.validation.Valid;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * &#064;description：付款单接口
 */
@ApiController(value = "IAMUserController", desc = "金蝶IAM同步用户接口，自定义插件")
public class IAMUserController {

    private final static Log logger = LogFactory.getLog(IAMUserController.class);//日志

    static CustomApiResult auditApiResultExt = new CustomApiResult();


    static UserResultExt userResultExt = new UserResultExt();
    @ApiPostMapping(value = "/shsh_iamUser", desc = "用户许可api接口")
    public CustomApiResult<@ApiResponseBody("返回参数") UserResultExt> resultExt
            (@NotNull @Valid @ApiRequestBody(value = "入参") UserModel model) throws ParseException {

        logger.info("进入用户许可api接口");

        //根据应用编码从缓存中获取应用信息
        AppInfo cgfwAppInfo = AppMetadataCache.getAppInfo("basedata");
        //获取应用的主键
        String appId = cgfwAppInfo.getId();
        AppCustomParam appCustomParam = new AppCustomParam(appId);
        Map<String, String> cusTomMap = SystemParamServiceHelper.loadAppCustomParameterFromCache(appCustomParam);
        boolean action = true;
        for (String value : cusTomMap.values()) {
            if (!value.equals("true")){
                userResultExt.setMsg("组织接口调用失败，错误原因：CCS暂未开启接受IAM人员参数");
                userResultExt.setData("");
                userResultExt.setTimestamp(new Timestamp(new Date().getTime()).toString());
                userResultExt.setCode("400");
                return CustomApiResult.success(userResultExt);
            }
        }
        RequestContext context = RequestContext.get();
        QFilter filter = new QFilter("name", QCP.equals, "文艺雄");//过滤条件
        DynamicObject userObj = QueryServiceHelper.queryOne("bos_user", "id,name", new QFilter[]{filter});
        RequestContext.copyAndSet(RequestContextService.copy(context, userObj.getString("id")));

        String jobName = model.getJobName();//岗位名称
        int sex = model.getSex();//性别
        String mobile = model.getMobile();//手机号
        String workNo = model.getWorkNo();//员工工号
        String pinyin = model.getPinyin();//姓名拼音
        String createTime = model.getCreateTime();//创建时间
        String orgCode = model.getOrgCode();//组织编码
        String name = model.getName();//名称
        String pwd = model.getPwd();//密码
        String account = model.getAccount();//账号
        String idNo = model.getIDNo();//证件编码
        int status = model.getStatus();//使用状态
        List<OrgsBean> orgs = model.getOrgs(); //人员挂靠的部门
        List<JobsBean> jobs = model.getJobs();

        List<UserParam> paramList = new ArrayList<>();
        UserParam user = new UserParam();

        //判断更新 还是删除 。是根据user的id 来判断的
        DynamicObject userInfo = BusinessDataServiceHelper.
                loadSingle("bos_user", new QFilter("number", "=", workNo).toArray());
        if(userInfo!=null){
            Long id = userInfo.getLong("id");
            user.setId(id);
            user.setCustomUserId(id);
        }
        Map<String, Object> dataMap = new HashMap<>();

        dataMap.put("number", workNo);
        dataMap.put("name", name);
        dataMap.put("username", account);
        dataMap.put("usertype", "1");
        dataMap.put("phone", mobile);
        dataMap.put("idcard", idNo);
        dataMap.put("gender", sex);
        if (userInfo!=null){
            dataMap.put("password",userInfo.getString("password"));
        }else {
            dataMap.put("password",pwd);
        }

        dataMap.put("fullpinyin", pinyin);
        Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(createTime);
        dataMap.put("createtime",date);
        dataMap.put("enable",status);


        List<Map<String, Object>> posList = new ArrayList<>();
        // 职位分录
        //根据orgs,更新人员所在的组织
        for(int n=0;n<orgs.size();n++){
            Map<String, Object> entryentity = new HashMap<>();
            OrgsBean orgsBean = orgs.get(n);
            String orgnum = orgsBean.getOrgCode();
            //根据orgnum找职位
            String jobname = jobs.stream()
                    .filter(job -> orgnum.equals(job.getOrgCode()))
                    .map(JobsBean::getJobName)
                    .findFirst()
                    .orElse(null);
            DynamicObject adminOrg = BusinessDataServiceHelper.
                    loadSingle("bos_adminorg", new QFilter("number", "=", orgnum).toArray());
            if (adminOrg==null){
                userResultExt.setMsg("人员接口调用失败，错误原因： 该人员部门编号在系统中未找到！");
                userResultExt.setData(workNo);
                userResultExt.setTimestamp(new Timestamp(new Date().getTime()).toString());
                userResultExt.setCode("400");
                break;
            }
            entryentity.put("dpt", adminOrg);
            entryentity.put("position", jobname);
            entryentity.put("isincharge", false); //负责人，统一为否，因为不费控涉及工作流
            if(orgCode.equals(orgnum)){ //为主职位
                entryentity.put("ispartjob", false);// 主要职位
            }else{
                entryentity.put("ispartjob", true);//兼职
            }

            entryentity.put("seq", n);
            posList.add(entryentity);
        }



        dataMap.put("entryentity", posList);
        user.setDataMap(dataMap);
        paramList.add(user);
//        kd.bos.servicehelper.user.UserServiceHelper.update();
        // 业务调用可以参照接口名，以下举例说明微服务调用方式
        IUserService userService = ServiceFactory.getService(IUserService.class);

        System.out.println();
//        if(userInfo!=null){
////            if((userInfo.getString("number")+userInfo.getString("enable")).equals(workNo+status)){
////                auditApiResultExt.setMessage("人员接口调用失败，错误原因：人员编码与状态与系统中的人员重复");
////                auditApiResultExt.setData(model);
////                auditApiResultExt.setStatus(false);
////                auditApiResultExt.setErrorCode("400");
////                return auditApiResultExt;
////            }else{
//                userService.update(paramList);
////            }
//        }else{
//            userService.add(paramList);
//        }

        UserServiceHelper.addOrUpdate(paramList);
        ArrayList<Long> longs = new ArrayList<>();
        // 判断执行结果
        for (UserParam result : paramList) {
            if (!result.isSuccess()) {
                userResultExt.setMsg("人员接口调用失败，错误原因：" + result.getMsg());
                userResultExt.setData(workNo);
                userResultExt.setTimestamp(new Timestamp(new Date().getTime()).toString());
                userResultExt.setCode("400");
                break;
            }else{
                longs.add(result.getId());
                userResultExt.setMsg("人员接口调用成功！");
                userResultExt.setData(workNo);
                userResultExt.setTimestamp(new Timestamp(new Date().getTime()).toString());
                userResultExt.setCode("0");
            }
        }
//        longs.add(new Long(123456789));
//        LicenseServiceHelper.addUserListByGroupId(2, longs);
        return CustomApiResult.success(userResultExt);
    }
}
